package com.xmut.mall.auth.service.impl;

import com.xmut.mall.auth.constant.AuthConstant;
import com.xmut.mall.auth.feign.MemberFeignService;
import com.xmut.mall.auth.service.PassWordService;
import com.xmut.mall.auth.utils.RespBean;
import com.xmut.mall.auth.vo.ResetPasswordVo;
import com.xmut.mall.auth.vo.ValidateCodeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class PassWordServiceImpl implements PassWordService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 校验验证码
     * @return
     */
    @Override
    public RespBean validateCode(ValidateCodeVo vo) {
        // 校验这个用户是否存在
        RespBean userByPhone = memberFeignService.getUserByPhone(vo.getMobile());
        if(userByPhone.getCode() == 500){
            return RespBean.error(userByPhone.getMessage());
        }

        String redisCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + vo.getMobile());
        if(!redisCode.equals(vo.getCode())){
            return RespBean.error("验证码错误");
        }else {
            String uuid = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(AuthConstant.SMS_RESETPASSWORD_CACHE_PREFIX+vo.getMobile(),uuid,5, TimeUnit.MINUTES);
            return RespBean.success("验证码正确",uuid);
        }
    }

    /**
     * 重置密码
     * @param vo
     * @return
     */
    @Override
    public RespBean resetPassword(ResetPasswordVo vo) {
        String redisUUID = redisTemplate.opsForValue().get(AuthConstant.SMS_RESETPASSWORD_CACHE_PREFIX + vo.getMobile());

        if (StringUtils.isEmpty(redisUUID)){
            return RespBean.error("该UUID不存在");
        }

        if(!redisUUID.equals(vo.getUuidCode())){
            // 如果redis中存储的uuid不存在或者错误
            return RespBean.error("UUID验证错误");
        }


        return memberFeignService.resetPassword(vo);
    }
}
